package Emulator;
import java.util.Vector;

import NodeInfo.NodeInfo;
import NodeInfo.NodeThread;

public class Emulator {

	private static int MaxNode=10;
	private static Vector<RangePair> pairs=new Vector<RangePair>();
	private static Vector<NodeThread> nodeThreads=new Vector<NodeThread>(MaxNode);

	public static void main(String[] args){
		for (int i=0;i<MaxNode;i++){
			NodeThread temThread=new NodeThread(i);
			nodeThreads.add(i,temThread);
			nodeThreads.get(i).start();
		}

		while(true){
			run();
			try {
				Thread.currentThread().sleep(5000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}

	public static void run() {
		if(IsAllConnected()){
			for(int i=0;i<=MaxNode;i++)
				nodeThreads.remove(i).stop();
		}
		for (int i=0;i<MaxNode;i++){
			synchronized(nodeThreads.get(i)){
				nodeThreads.get(i).notify();
			}
		}
	}

	public static void calculateConstant(){

	}

	public static void CreateNodeThread(){

	}

	public static double calculateEuclidianDistance(float xd, float yd, float x1, float y1){
		return Math.sqrt(Math.pow((xd-x1), 2)+Math.pow((yd-y1), 2));
	}


	public static boolean IsAllConnected(){
		return false;
	}

	public static Vector<RangePair> whoAreMyNeighbors(int myId){
		Vector<RangePair> neighbors = new Vector<RangePair>();
		for(NodeThread n:nodeThreads){
			double d=calculateEuclidianDistance(n.getNodeinfo().getXpos(), 
					n.getNodeinfo().getYpos(), nodeThreads.get(myId).getNodeinfo().getXpos(),
					nodeThreads.get(myId).getNodeinfo().getYpos());
			if(d<=nodeThreads.get(myId).getNodeinfo().getMaxTxRange() && n.getNodeinfo().getNodeId()!=myId){
				RangePair p = new RangePair();
				p.setA(n.getNodeinfo());
				p.setDistance(d);
				neighbors.add(p);
			}
		}
		return neighbors;
	}

	public static boolean SendMsg(String msg, int source, int destination){
		Vector<RangePair> possibleDests = whoAreMyNeighbors(source);
		boolean ret=false;
		for(RangePair p:possibleDests){
			if(p.getA().getNodeId()==destination){
				nodeThreads.get(destination).getNodeinfo().getReceivedMsgs().add(msg);
				ret=true;
				break;
			}
		}
		return ret;
	}
}